<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Services\CommonManager;
use App\Http\Services\FileManager;
use App\UnitBindVipPackage;
use App\Units;
use App\VipInfo;
use App\VipPackage;
use App\VipPackageXRule;
use App\VipRule;
use http\Client\Curl\User;
use http\Env\Response;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class OperationController extends Controller
{
    /**
     * 获取付费套餐
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getVipPackageList(Request $request){
        $limit          = !is_null($request->get('limit')) ? $request->get('limit') : 10;
        $page           = !is_null($request->get('page')) ? $request->get('page') : 1;

        $pageInfo = [
            'limit' => $limit,
            'page' => $page
        ];

        /** @var VipPackage $vipPackage */
        $vipPackageList = VipPackage::whereNull('deleted_at');

        $pageInfo['total'] = $vipPackageList->count();

        $vipPackageList = $vipPackageList->orderBy('sort','asc')->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();
        if(count($vipPackageList) > 0){
            foreach($vipPackageList as $vipPackage){
                if($vipPackage->status == 1){
                    $vipPackage->status_name = '开启';
                }else{
                    $vipPackage->status_name = '关闭';
                }

                $vipPackage->is_use = CommonManager::vipPackageWhetherUse($vipPackage->id);

                $vipPackage->is_use_name = CommonManager::vipPackageWhetherUse($vipPackage->id) ? '是' : '否';

            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $vipPackageList,'page_info' => $pageInfo]);
    }

    /**
     * 获取套餐详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getVipPackageDetail(Request $request){
        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $vipPackage = VipPackage::whereId($id)->first();
        if($vipPackage){
            $vipRuleInfoArr = [];
            /** @var VipRule $vipRule */
            $vipRuleList = VipRule::orderBy('created_at','desc')->get();
            if(count($vipRuleList) > 0){
                foreach ($vipRuleList as $vipRule) {
                    $num = 0;
                    $isHave = 0;
                    $enterType = 0;
                    $VipPackageXRule = VipPackageXRule::whereVipPackageId($vipPackage->id)->whereVipRuleId($vipRule->id)->first();
                    if($VipPackageXRule){
                        if($vipRule->mark == 'release_demand' || $vipRule->mark == 'butt_demand' || $vipRule->mark == 'push_demand'){
                            $num = $VipPackageXRule->today_run_num;

                            $enterType = 1;
                        }else{
                            $num = 1;
                        }

                        $isHave = 1;
                    }


                    $data = (object)['id' => $vipRule->id,'vip_rule_name' => $vipRule->name,'enter_type' => $enterType,'is_have' => $isHave,'num' => $num];


                    array_push($vipRuleInfoArr,$data);
                }
            }

            $vipPackage->vip_rule_list = $vipRuleInfoArr;
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $vipPackage]);
    }

    /**
     * 改变套餐状态
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function changeVipPackageStatus(Request $request){
        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $vipPackage = VipPackage::whereId($id)->first();
        if(!$vipPackage)
            return response()->json(['level' => 'error','message' => '付费套餐不存在']);

        if($vipPackage->status == 1){
            $vipPackage->status = 0;
        }else{
            $vipPackage->status = 1;
        }

        $vipPackage->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $vipPackage]);
    }

    /**
     * 获取用户权益
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getVipRuleList(Request $request){
        $vipRuleList = VipRule::all();
        if(count($vipRuleList) > 0){
            foreach($vipRuleList as $vipRule){
                $enterType = 0;
                if($vipRule->mark == 'release_demand' || $vipRule->mark == 'butt_demand' || $vipRule->mark == 'push_demand'){
                    $enterType = 1;
                }

                $vipRule->enter_type = $enterType;
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $vipRuleList]);
    }

    /**
     * 设置付费套餐
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setVipPackage(Request $request){
        $id         = !is_null($request->get('id')) ? $request->get('id') : 0;
        $name       = !is_null($request->get('name')) ? $request->get('name') : '';
        $keepTime   = !is_null($request->get('keep_time')) ? $request->get('keep_time') : 0;
        $free       = !is_null($request->get('free')) ? $request->get('free') : 0.00;
        $sort       = !is_null($request->get('sort')) ? $request->get('sort') : 0;
        $vipRuleIds = $request->get('vip_rule_ids');

        if($name == '')
            return response()->json(['level' => 'error','message' => '请输入套餐名称']);

        if($keepTime <= 0)
            return response()->json(['level' => 'error','message' => '请选择收费周期']);

        if($free < 0)
            return response()->json(['level' => 'error','message' => '请正确输入价格']);

        if(!is_array($vipRuleIds) || (is_array($vipRuleIds) && count($vipRuleIds) <= 0))
            return response()->json(['level' => 'error','message' => '请选择权益']);

        $vipPackage = VipPackage::whereId($id)->first();
        if(!$vipPackage){
            $vipPackage = new VipPackage();
        }else{
            $isUse = CommonManager::vipPackageWhetherUse($vipPackage->id);
            if($isUse)
                return response()->json(['level' => 'error','message' => '用户使用中，不能修改']);
        }

        $vipPackage->name        = $name;
        $vipPackage->free        = $free;
        $vipPackage->keep_time   = $keepTime;
        $vipPackage->sort        = $sort;
        $vipPackage->status      = 1;
        $vipPackage->save();

        $vipPackageXRuleList = VipPackageXRule::whereVipPackageId($vipPackage->id)->get();
        if(count($vipPackageXRuleList) > 0){
            foreach($vipPackageXRuleList as $vipPackageXRule){
                $vipPackageXRule->forceDelete();
            }
        }

        foreach($vipRuleIds as $vipRuleId){
            $newVipPackageXRule = new VipPackageXRule();
            $newVipPackageXRule->vip_package_id = $vipPackage->id;
            $newVipPackageXRule->vip_rule_id    = $vipRuleId['id'];
            $newVipPackageXRule->today_run_num  = $vipRuleId['num'];
            $newVipPackageXRule->save();
        }

        return response()->json(['level' => 'success','message' => '设置成功','data' => $vipPackage]);
    }

    /**
     * 删除套餐
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function delVipPackage(Request $request){
        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $vipPackage = VipPackage::whereId($id)->first();
        if(!$vipPackage)
            return response()->json(['level' => 'error','message' => '付费套餐不存在']);

        $isUse = CommonManager::vipPackageWhetherUse($vipPackage->id);
        if($isUse)
            return response()->json(['level' => 'error','message' => '用户使用中，不能删除']);

        $vipPackageXRuleList = VipPackageXRule::whereVipPackageId($vipPackage->id)->get();
        if(count($vipPackageXRuleList) > 0){
            foreach($vipPackageXRuleList as $vipPackageXRule){
                $vipPackageXRule->delete();
            }
        }

        $vipPackage->delete();

        return response()->json(['level' => 'success','message' => '删除成功','data' => $vipPackage]);
    }

    /**
     * 获取绑定该套餐的单位列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getBindPackageMemberUnitList(Request $request){
        $vipPackageId  = !is_null($request->get('vip_package_id')) ? $request->get('vip_package_id') : 0;
        $limit         = !is_null($request->get('limit')) ? $request->get('limit') : 8;
        $page          = !is_null($request->get('page')) ? $request->get('page') : 1;

        $pageInfo = [
            'limit' => $limit,
            'page' => $page,
        ];

        /** @var UnitBindVipPackage $unit */
        $unitList = UnitBindVipPackage::whereVipPackageId($vipPackageId)->where('end_time','>',date('Y-m-d H:i:s',time()));

        $pageInfo['total'] = $unitList->count();

        $unitList = $unitList->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();
        if(count($unitList) > 0){
            foreach ($unitList as $unit){
                $unitInfo = Units::whereId($unit->unit_id)->first();
                if($unitInfo){
                    $unitInfo->photo_url = FileManager::getImgUrl($unitInfo->photo_id);

                    $auth_employeeNum_num   = CommonManager::getUnitAuthNumToUnitId($unit->unit_id,0);
                    $auth_admin_num         = CommonManager::getUnitAuthNumToUnitId($unit->unit_id,1);

                    $unit->bind_user_num = $auth_employeeNum_num + $auth_admin_num;
                }

                $unit->unit_info = $unitInfo;
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $unitList,'page_info' => $pageInfo]);
    }

    /**
     * 套餐绑定到单位
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function vipPackageBindUnit(Request $request){
        $unitId       = !is_null($request->get('unit_id')) ? $request->get('unit_id') : 0;
        $userId       = !is_null($request->get('user_id')) ? $request->get('user_id') : 0;
        $vipPackageId = !is_null($request->get('vip_package_id')) ? $request->get('vip_package_id') : 0;
        $num          = !is_null($request->get('num')) ? $request->get('num') : 1;
        $type         = !is_null($request->get('type')) ? $request->get('type') : 'unit';

        if($type == 'unit'){
            $unit = Units::whereId($unitId)->first();
            if(!$unit)
                return response()->json(['level' => 'error','message' => '单位不存在']);

            if($unit->is_member_unit != 1)
                return response()->json(['level' => 'error','message' => '该单位不是会员单位,不能绑定套餐']);

            $vipPackage = VipPackage::whereId($vipPackageId)->first();
            if(!$vipPackage)
                return response()->json(['level' => 'error','message' => '套餐不存在']);

            $vipPackageBindUnit = UnitBindVipPackage::whereUnitId($unit->id)->first();
            if($vipPackageBindUnit){
                if($vipPackageBindUnit->vip_package_id == $vipPackage->id){
                    if(strtotime($vipPackageBindUnit->end_time) > time()){
                        $vipPackageBindUnit->vip_package_id     = $vipPackage->id;
                        $vipPackageBindUnit->end_time           = date("Y-m-d H:i:s",strtotime($vipPackageBindUnit->end_time) + ($vipPackage->keep_time * 30 * 24 * 3600) * (int)$num);
                        $vipPackageBindUnit->save();
                    }else{
                        $vipPackageBindUnit->vip_package_id     = $vipPackage->id;
                        $vipPackageBindUnit->start_time         = date("Y-m-d H:i:s",time());
                        $vipPackageBindUnit->end_time           = date("Y-m-d H:i:s",time() + ($vipPackage->keep_time * 30 * 24 * 3600) * (int)$num);
                        $vipPackageBindUnit->save();
                    }
                }else{
                    if(strtotime($vipPackageBindUnit->end_time) > time()){
                        return response()->json(['level' => 'error','message' => '该单位已经保定过其他套餐了']);
                    }else{
                        $vipPackageBindUnit->vip_package_id     = $vipPackage->id;
                        $vipPackageBindUnit->start_time         = date("Y-m-d H:i:s",time());
                        $vipPackageBindUnit->end_time           = date("Y-m-d H:i:s",time() + ($vipPackage->keep_time * 30 * 24 * 3600) * (int)$num);
                        $vipPackageBindUnit->save();
                    }
                }

            }else{
                $vipPackageBindUnit = new UnitBindVipPackage();
                $vipPackageBindUnit->unit_id        = $unit->id;
                $vipPackageBindUnit->vip_package_id = $vipPackage->id;
                $vipPackageBindUnit->start_time         = date("Y-m-d H:i:s",time());
                $vipPackageBindUnit->end_time           = date("Y-m-d H:i:s",time() + ($vipPackage->keep_time * 30 * 24 * 3600) * (int)$num);
                $vipPackageBindUnit->save();
            }
        }elseif($type == 'user'){
            $user = \App\User::whereId($userId)->whereRole(0)->first();
            if(!$user)
                return response()->json(['level' => 'error','message' => '用户不存在']);

            $vipPackage = VipPackage::whereId($vipPackageId)->first();
            if(!$vipPackage)
                return response()->json(['level' => 'error','message' => '套餐不存在']);

            $vipInfo = VipInfo::whereUserId($user->id)->first();
            if($vipInfo){
                if($vipInfo->vip_package_id == $vipPackage->id){
                    if(strtotime($vipInfo->end_time) > time()){
                        $vipInfo->vip_package_id     = $vipPackage->id;
                        $vipInfo->end_time           = date("Y-m-d H:i:s",strtotime($vipInfo->end_time) + ($vipPackage->keep_time * 30 * 24 * 3600) * (int)$num);
                        $vipInfo->save();
                    }else{
                        $vipInfo->vip_package_id     = $vipPackage->id;
                        $vipInfo->start_time         = date("Y-m-d H:i:s",time());
                        $vipInfo->end_time           = date("Y-m-d H:i:s",time() + ($vipPackage->keep_time * 30 * 24 * 3600) * (int)$num);
                        $vipInfo->save();
                    }
                }else{
                    if(strtotime($vipInfo->end_time) > time()){
                        return response()->json(['level' => 'error','message' => '该用户已经保定过其他套餐了']);
                    }else{
                        $vipInfo->vip_package_id     = $vipPackage->id;
                        $vipInfo->start_time         = date("Y-m-d H:i:s",time());
                        $vipInfo->end_time           = date("Y-m-d H:i:s",time() + ($vipPackage->keep_time * 30 * 24 * 3600) * (int)$num);
                        $vipInfo->save();
                    }
                }
            }else{
                $vipInfo = new VipInfo();
                $vipInfo->user_id            = $user->id;
                $vipInfo->vip_package_id     = $vipPackage->id;
                $vipInfo->start_time         = date("Y-m-d H:i:s",time());
                $vipInfo->end_time           = date("Y-m-d H:i:s",time() + ($vipPackage->keep_time * 30 * 24 * 3600) * (int)$num);
                $vipInfo->status             = 1;
                $vipInfo->save();
            }

        }else{
            return response()->json(['level' => 'error','message' => '绑定类型错误']);
        }



        return response()->json(['level' => 'success','message' => '绑定成功']);
    }

    /**
     * 解除单位绑定的套餐
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function UnitUntieVipPackage(Request $request){
        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $vipPackageBindUnit = UnitBindVipPackage::whereId($id)->where('end_time','>',date('Y-m-d H:i:s',time()))->first();
        if(!$vipPackageBindUnit)
            return response()->json(['level' => 'error','message' => '操作失败']);

        $vipPackageBindUnit->delete();

        return response()->json(['level' => 'success','message' => '解绑成功','data' => $vipPackageBindUnit]);
    }

    /**
     * 获取用户权益
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserRightsList(Request $request){
        $limit          = !is_null($request->get('limit')) ? $request->get('limit') : 10;
        $page           = !is_null($request->get('page')) ? $request->get('page') : 1;
        $type           = !is_null($request->get('type')) ? $request->get('type') : 'default';

        $pageInfo = [
            'limit' => $limit,
            'page' => $page
        ];

        /** @var VipPackage $vipPackage */
        $vipPackageList = VipPackage::whereNull('deleted_at');

        if($type == 'user'){
            $vipPackageList->whereStatus(1);
        }

        $pageInfo['total'] = $vipPackageList->count();

        $vipPackageList = $vipPackageList->orderBy('sort','asc')->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();
        if(count($vipPackageList) > 0){
            foreach($vipPackageList as $vipPackage){
                $vipRuleInfoArr = [];
                /** @var VipRule $vipRule */
                $vipRuleList = VipRule::orderBy('created_at','desc')->get();
                if(count($vipRuleList) > 0){
                    foreach ($vipRuleList as $vipRule) {
                        $isHave = '无';

                        $VipPackageXRule = VipPackageXRule::whereVipPackageId($vipPackage->id)->whereVipRuleId($vipRule->id)->first();
                        if($VipPackageXRule){
                            if($vipRule->mark == 'release_demand' || $vipRule->mark == 'butt_demand' || $vipRule->mark == 'push_demand'){
                                if($VipPackageXRule->today_run_num == -1){
                                    $isHave = '无限';
                                }elseif($VipPackageXRule->today_run_num > 0){
                                    $isHave = $VipPackageXRule->today_run_num.'个/天';
                                }
                            }else{
                                $isHave = '有';
                            }
                        }

                        $data = (object)['id' => $vipRule->id,'vip_rule_name' => $vipRule->name,'value' => $isHave];

                        array_push($vipRuleInfoArr,$data);
                    }
                }

                $vipPackage->vip_rule_list = $vipRuleInfoArr;
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $vipPackageList,'page_info' => $pageInfo]);
    }
}
